<template>
  <div class="bottomCard-root">
    <lark-card border :radius="false" :show-title="false" body-width="75vw" body-height="30vh">
      <div class="bottomCard-body">
        <div class="bottomCard-body-header">
          <div>
            <btn-tabs :default-active="0" :items="[{ name: '种植信息', value: 1 }]"></btn-tabs>
          </div>
          <div class="bottomCard-body-header-operation">
            <el-button size="mini" type="success" @click="addBtn">新增</el-button>
            <div class="bottomCard-body-header-close" @click="closeAction">
              <i class="el-icon-error"></i>
            </div>
          </div>
        </div>

        <div class="bottomCard-body-list">
          <div class="bottomCard-body-table" id="bottomCard-body-table">
            <plant-table @goDetail="goDetail" @rowClick="rowClick" v-loading="tableLoading" :table-data="tableData"></plant-table>

          </div>
          <div class="bottomCard-body-pagination">
            <el-pagination
              small
              layout="prev, pager, next"
              :total="pageInfo.total"
              :current-page="pageInfo.pageNum"
              :page-size="pageInfo.pageSize"
              @current-change="pageChange"
            >
            </el-pagination>
          </div>
        </div>

      </div>
    </lark-card>
    <lark-card border :x="300" :y="100" body-height="600px" :body-width="'500px'" v-if="editDataVisible" :hidden="!editDataVisible"
               @closeAction="editDataVisible = !editDataVisible"
               card-title="地块信息" draggable
               :radius="false">

      <div class="edit-fil">
        <div class="edit-fil-form">
          <el-scrollbar>
            <div class="edit-fil-container">
              <el-form :ref="formRef" :model="editDataForm" label-width="80px" :rules="rules">
                <el-form-item label="区域">
                  {{`${editDataForm.measurementArea}亩`}}
                  <el-button round size="mini" @click="selectArea">选择区域</el-button>
                </el-form-item>

                <el-form-item label="地块名称" prop="name">
                  <el-input v-model="editDataForm.name" size="mini"></el-input>
                </el-form-item>
                <el-form-item label="品名" prop="partName">
                  <el-input v-model="editDataForm.partName" size="mini"></el-input>
                </el-form-item>
                <el-form-item label="类型" prop="type">
                  <el-input v-model="editDataForm.type" size="mini"></el-input>
                </el-form-item>
                <el-form-item label="建植时间" prop="buildData">
                  <el-date-picker
                    size="mini"
                    v-model="editDataForm.buildData"
                    type="date"
                    value-format="yyyy-MM-dd"
                    placeholder="选择日期">
                  </el-date-picker>
                </el-form-item>
                <el-form-item label="建植方式" prop="type">
                  <el-input v-model="editDataForm.buildMode" size="mini"></el-input>
                </el-form-item>

                <el-form-item label="株距*行距" prop="rowDistance">
                  <el-input type="number" v-model="editDataForm.rowDistance" size="mini"></el-input>
                </el-form-item>
                <el-form-item label="实际种植面积(亩)" prop="plantArea">
                  <el-input type="number" v-model="editDataForm.plantArea" size="mini"></el-input>
                </el-form-item>

                <el-form-item label="是否补苗" prop="isFillSeedlings">
                  <el-radio-group v-model="editDataForm.isFillSeedlings">
                    <el-radio :label="`是`">是</el-radio>
                    <el-radio :label="`否`">否</el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item label="负责人" prop="dutyUserId">
                  <div class="u-l-container"
                       v-if="editDataForm && editDataForm.dutyUserId && Array.isArray(editDataForm.dutyUserId) && editDataForm.dutyUserId.length > 0">
                    <el-scrollbar>
                      <el-tag
                        style="margin-right: 5px"
                        v-for="user in editDataForm.dutyUserId"
                        :key="user.userName"
                        closable
                        type="info"
                        @close="userRemove(user)">
                        {{ user.nickName }}
                      </el-tag>
                    </el-scrollbar>
                  </div>
                  <el-button @click="selectUserVisible = true" size="small">选择</el-button>
                </el-form-item>


              </el-form>
            </div>
          </el-scrollbar>
        </div>
        <div class="edit-fil-footer">
          <el-button :loading="submitBtnLoading" @click="submit" round>确定</el-button>
        </div>
      </div>

    </lark-card>


    <lark-card border card-title="选择负责人" :x="500" :radius="false" v-if="selectUserVisible" :hidden="!selectUserVisible"
               body-width="700px" body-height="550px"
               @closeAction="selectUserVisible = !selectUserVisible" draggable>
      <div class="select-user-body">
        <user-select v-model="editDataForm.dutyUserId"></user-select>
        <div style="width: 100%;text-align: right;padding-right:20px">
          <el-button @click="selectUserVisible = false">确定</el-button>
        </div>
      </div>
    </lark-card>
  </div>
</template>

<script>
  import { reactive, toRefs, onMounted, ref, watch, computed } from '@vue/composition-api'
  import btnTabs from '@/components/ServiceComponents/btnTabs'
  import plantTable from '@/views/industry/cpf/bottomCard/plantTable'
  import { selectInfo, deleteInfo, updateInfo, insertInfo } from '@/api/industry/cpf'
  import { Message } from 'element-ui'
  import { MathUtil } from 'lark-utils'
  import { planarArea, clearDrawGeometry, draw, highlightByGeometryList, removeHighlight, getGeometryListByQueryResult, queryResultsByUrls } from 'lark-map'
  import userSelect from '@/components/ServiceComponents/userSelect'
  import router from '@/router'

  export default {
    name: 'bottomCard',
    props: {
      baseId: {
        type: [String, Number],
        default: null
      },
      mapView: {
        type: Object,
        default: () => {
          return null
        }
      }
    },
    components: {
      userSelect,
      plantTable,
      btnTabs
    },
    setup(props, content) {
      let data = reactive({
        selectUserVisible: false,
        formRef: `formRef${MathUtil.guid()}`,
        submitBtnLoading: false,
        tableLoading: false,
        editDataVisible: false,
        pageInfo: {
          total: 0,
          pageNum: 1,
          pageSize: 5
        },
        tableData: [],
        tabs: 1,
        rules: {},
        editDataForm: {
          /** 地块名称 */
          name: null,
          /** 品名 */
          partName: null,
          /** 类型 */
          type: null,
          /** 建植时间 */
          buildData: null,
          /** 建植方式 */
          buildMode: null,
          /** 株距*行距 */
          rowDistance: null,
          /** 实际种植面积 */
          plantArea: null,//填写
          /** 是否补苗 */
          isFillSeedlings: '是',
          /** 测量面积 */
          measurementArea: 0,//面得出
          /** 负责人 */
          dutyUserId: []//选择
        },
        editResetForm: {}
      })

      watch(() => props.baseId, () => {
        loadListData()
      })
      watch(() => data.editDataVisible, (newVal) => {
        if (!newVal) {
          clearDrawGeometry({ view: props.mapView })
        }
      })
      const goDetail = (row) => {
        router.push({ path: '/cpf/plantDetail', query: { id: row.id, baseId: props.baseId } })
      }
      const closeAction = () => {
        content.emit('closeSelfAction')
      }
      const addBtn = () => {
        resetFormData()
        data.editDataVisible = true
      }
      const resetFormData = () => {
        data.editDataForm = data.editResetForm
      }
      const tabsChange = async(item) => {
        data.tabs = item.value
        data.pageInfo.pageNum = 1
        await loadListData()
      }
      const pageChange = async(currentPage) => {
        data.pageInfo.pageNum = currentPage
        await loadListData()
      }

      const userRemove = (user) => {
        data.editDataForm.dutyUserId = data.editDataForm.dutyUserId.filter(item => item.userId !== user.userId)
        data.editDataForm = JSON.parse(JSON.stringify(data.editDataForm))
      }

      const selectArea = async() => {
        let graphic = await draw({ type: 'polygon', view: props.mapView })
        data.editDataForm.rings = JSON.stringify(graphic.geometry.rings[0])
        let area = planarArea({ geometry: graphic.geometry })
        data.editDataForm.measurementArea = (area * 10000 * 1500).toFixed(2)
      }

      const rowClick = async row => {
        // content.emit('rowClick', row)

        let requestParams = {
          view: props.mapView,
          idList: ['SeedFarmService'],
          outFields: [{ parentId: 'SeedFarmService', value: ['*'] }],
          where: [{ parentId: 'SeedFarmService', value: `1=1 and id = '${row.id}'` }],
          returnGeometry: [{ parentId: 'SeedFarmService', value: true }],
          subLayerIds: [{ parentId: 'SeedFarmService', value: [2] }]
        }

        let res = await queryResultsByUrls(requestParams)
        let geometryList = getGeometryListByQueryResult({ res, merge: true })
        if (!geometryList?.length) {
          Message.warning('没有查询结果')
          removeHighlight(props.mapView)
          return
        }
        highlightByGeometryList({ view: props.mapView, geometryList: geometryList, zoom: true })
      }

      const loadListData = async() => {
        try {
          if (props.baseId == null) {
            return
          }
          removeHighlight(props.mapView)
          data.tableLoading = true
          let response = await selectInfo({ baseId: props.baseId, ...data.pageInfo })
          data.tableData = response.rows
          data.pageInfo.total = response.total
        } finally {
          data.tableLoading = false
        }
      }

      const submit = async() => {
        //提交表单
        try {
          content.refs[`${data.formRef}`].validate(async valid => {
            if (valid) {
              if (data.editDataForm.rings.length == 0) {
                Message.error(`区域不能为空`)
                return
              }
              data.submitBtnLoading = true
              await insertInfo({ baseId: props.baseId, ...data.editDataForm })

              Message.success('操作成功')
              loadListData()
              data.editDataVisible = false
            }
          })

        } finally {
          data.submitBtnLoading = false
        }
      }

      onMounted(() => {
        loadListData()
        data.editResetForm = JSON.parse(JSON.stringify(data.editDataForm))
      })
      return { ...toRefs(data), closeAction, tabsChange, pageChange, rowClick, addBtn, submit, selectArea, userRemove, goDetail }
    }
  }
</script>

<style scoped lang="scss">
  $header-height: 20px;
  .bottomCard-root {
    .bottomCard-body {
      .bottomCard-body-list {
        .bottomCard-body-table {
          height: calc(30vh - 50px);
        }

        .bottomCard-body-pagination {

        }
      }

      .bottomCard-body-header {
        display: flex;
        flex-direction: row;
        justify-content: space-between;
        height: $header-height;
        box-sizing: border-box;

        .bottomCard-body-header-tabs {

        }

        .bottomCard-body-header-operation {
          display: flex;
        }

        .bottomCard-body-header-close {
          margin-left: 20px;
          font-size: 20px;
          color: red;

          &:hover {
            cursor: pointer;
          }
        }
      }
    }
  }
</style>
<style lang="scss">
  .bottomCard-root {
    .bottomCard-body {
      .bottomCard-body-header {
        .bottomCard-body-header-operation {
          .el-button.el-button--success.el-button--mini {
            padding-top: 5px;
            padding-bottom: 5px;
          }
        }
      }
    }
  }

  .edit-fil {
    padding: 10px 5px;

    .edit-fil-form {
      .edit-fil-container {
        padding: 0px 10px;
      }

      height: calc(598px - 20px - 40px);
      padding-bottom: 10px;
    }

    .edit-fil-footer {
      height: 40px;
      text-align: right;
      margin-right: 10px;
      margin-top: 10px;
    }
  }
</style>
